package cytj.setup.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import cytj.setup.R;


/**
 * 蓝牙搜索列表的Activity
 * Created by LTP on 2015/12/14
 */
public class BluetoothDeviceListActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener {
    /**
     * 获取默认的蓝牙适配器
     */
    private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    /**
     * 搜索和取消搜索蓝牙按键
     */
    private Button button_search_bluetooth;
    /**
     * 搜索到的蓝牙设备列表的ListView的适配器
     */
    private ArrayAdapter<String> adapter;
    /**
     * 装载搜索到的蓝牙设备列表的集合
     */
    private List<String> bluetoothDeviceList = new ArrayList<>();
    /**
     * 注册一个广播接收者
     */
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                bluetoothDeviceList.add(device.getName() + "：" + device.getAddress());
                adapter.notifyDataSetChanged();
            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                button_search_bluetooth.setText("搜索蓝牙");
                setProgressBarIndeterminateVisibility(false);
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_bluetooth_device_list);
        initView();
        initIntentFilter();
    }

    /**
     * 控件初始化
     */
    private void initView() {
        button_search_bluetooth = (Button) findViewById(R.id.button_search_bluetooth_BluetoothDeviceListActivity);
        button_search_bluetooth.setOnClickListener(this);
        // 取消搜索蓝牙和退出当前界面以及关闭蓝牙的按键
        findViewById(R.id.button_cancel_search_bluetooth_BluetoothDeviceListActivity).setOnClickListener(this);
        // 装载搜索到的蓝牙设备列表的ListView
        ListView listView_device = (ListView) findViewById(R.id.listView_device_BluetoothDeviceListActivity);
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, bluetoothDeviceList);
        listView_device.setAdapter(adapter);
        listView_device.setOnItemClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_search_bluetooth_BluetoothDeviceListActivity:
                // 点击搜索蓝牙按键
                setProgressBarIndeterminateVisibility(true);
                button_search_bluetooth.setText("正在搜索...");
                if (bluetoothAdapter.isDiscovering()) {
                    bluetoothAdapter.cancelDiscovery();
                } else {
                    bluetoothDeviceList.clear();
                    bluetoothAdapter.startDiscovery();
                }
                break;
            case R.id.button_cancel_search_bluetooth_BluetoothDeviceListActivity:
                //点击取消按键
                bluetoothAdapter.cancelDiscovery();
                onBackPressed();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // 点击蓝牙设备列表项
        bluetoothAdapter.cancelDiscovery();
        String info = bluetoothDeviceList.get(position);
        // 获取点击蓝牙列表项的蓝牙Mac地址
        String macAddress = info.substring(info.length() - 17);
        Intent intent = new Intent();
        intent.putExtra("macAddress", macAddress);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

    /**
     * 注册广播过滤器
     */
    private void initIntentFilter() {
        IntentFilter mIntentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(broadcastReceiver, mIntentFilter);
        mIntentFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(broadcastReceiver, mIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //当活动（页面）销毁时，取消注册广播过滤器
        unregisterReceiver(broadcastReceiver);
    }
}
